// pages/peccancy/waite-offer.js
const app = getApp()
var total_micro_second = 0;
// var total_micro_second = 24 * 60 * 60 * 60;

/* 毫秒级倒计时 */
function count_down(that) {
    // 渲染倒计时时钟
    that.setData({
        clock: date_format(total_micro_second)
    });

    if (total_micro_second <= 0) {
        that.setData({
            clock: "已经截止"
        });
        // timeout则跳出递归
        return;
    }
    setTimeout(function() {
        // 放在最后--
        total_micro_second -= 10;
        count_down(that);
    }, 10)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
    // 秒数
    var second = Math.floor(micro_second / 1000);
    // 小时位
    var hr = Math.floor(second / 3600);
    // 分钟位
    var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
    // 秒位
    var sec = fill_zero_prefix((second - hr * 3600 - min * 60)); // equal to => var sec = second % 60;
    // 毫秒位，保留2位
    // var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

    return hr + ":" + min + ":" + sec + " ";
}

// 位数不足补零
function fill_zero_prefix(num) {
    return num < 10 ? "0" + num : num
}

Page({
    data: {
        clock: '',
        is_redirect: true
    },
    onLoad: function(options) {
		options.count_down_time = (wx.getStorageSync('TICKET_QUOTE_TIME') * 100) / 100
        this.setData(options)
        this.loadData()
    },
    loadData() {
        wx.showLoading({
            title: '加载中...',
        })
        app.http.post('rest/ticket/queryById', {
            data: this.data.id
        }).then(res => {
            wx.hideLoading()
            let create_time = res.obj.createTime.replace(new RegExp("-", "gm"), "/")
            let current_time = new Date().getTime()
            let end_time = res.obj.endTime.replace(new RegExp("-", "gm"), "/")
            create_time = (new Date(create_time)).getTime()
            total_micro_second = (create_time + (this.data.count_down_time * 60 * 60 * 1000)) - current_time
            count_down(this)
            this.setData({
                info: res.obj
            })
        }).catch(err => {
            wx.hideLoading()
            app.wxToast.error(err.data.mag)
        })

    },
    onUnload() {
        this.data.is_redirect && wx.redirectTo({
            url: '/pages/car-owner/personal/my-peccancy',
        })
    },
    backindex() {
        this.setData({
            is_redirect: false
        })
        wx.navigateBack({
            delta: 4
        })
    }
})